﻿namespace FluentMvc
{
    using System.Collections.Generic;
    using System.Linq.Expressions;
    using System.Reflection;
    using System.Linq;

    public class ExpressionHandler : ExpressionVisitor
    {
        private readonly List<string> propertyNames = new List<string>();
        public string GetFullPropertyName(Expression expression)
        {
            Visit(expression);
            propertyNames.Reverse();
            return string.Join(".", propertyNames);
        }

        public string GetPropertyName(Expression expression)
        {
            Visit(expression);
            return propertyNames.First();
        }

        private MethodInfo info;
        public MethodInfo GetMethod(Expression expression)
        {
            Visit(expression);
            return info;
        }

        protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            var test = (ConstantExpression)node.Arguments[2];
            info = (MethodInfo)test.Value;
            return base.VisitMethodCall(node);
        }

        protected override Expression VisitMember(MemberExpression node)
        {
            if (node.Member.MemberType == MemberTypes.Property)
            {
                propertyNames.Add(node.Member.Name);
            }
            return base.VisitMember(node);
        }
    }
}